import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "../utils/api";
import SockJS from 'sockjs-client';
import Stomp from 'stompjs'
import {Notification} from 'element-ui';

Vue.use(Vuex);
const now = new Date();
const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        //除当前用户之外的所有操作员
        admins: [],
        //当前登录用户
        currentAdmin: JSON.parse(window.sessionStorage.getItem('user')),
        currentSession: null,
        filterKey: '',
        stomp: null,
        isDot: {},
    },

    mutations: {
        /*初始化菜单*/
        initRoutes(state, data) {
            state.routes = data;
        },
        changeCurrentSession(state, currentSession) {
            state.currentSession = currentSession;
            Vue.set(state.isDot, state.currentAdmin.username + '#' + state.currentSession.username, false);
        },
        /**
         * 用来保存消息内容
         * @param state
         * @param msg
         */
        addMessage(state, msg) {
            let mss = state.sessions[state.currentAdmin.username + '#' + msg.to];
            if (!mss) {
                /* state.sessions[state.currentAdmin.username + '#' + msg.to] = [];*/
                Vue.set(state.sessions, state.currentAdmin.username + '#' + msg.to, [])
            }
            state.sessions[state.currentAdmin.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.notSelf
            })


        },
        INIT_DATA(state) {
            //浏览器本地的历史聊天记录
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        /**
         * 把用户列表数据存在vuex中
         * @param state
         * @param data
         * @constructor
         */
        INIT_ADMINS(state, data) {
            state.admins = data;
        },
        INIT_ADMIN(state, admin) {
            state.currentAdmin = admin;
        }
    },
    actions: {
        /**
         * 初始化用户数据，该方法在FriendChat组件中的mounted函数调用了
         * @param context 上下文
         */
        initData(context) {
            context.commit('INIT_DATA');
            getRequest('/chat/getAllAdmins').then(res => {
                if (res) {
                    context.commit('INIT_ADMINS', res);
                }
            });
        },
        /**
         * 在线聊天功能 发送/接收消息
         * @param context
         */
        connect(context) {
            //连接ws/ep的端点
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            //获取token
            let token = window.sessionStorage.getItem('tokenStr');
            //配置连接参数
            context.state.stomp.connect({'Auth-Token': token}, success => {
                //订阅消息，user/queue/chat是后台配置的
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    let receiveMsg = JSON.parse(msg.body);
                    //如果接收到消息，没有在聊天界面或者聊天的不是当前展示的人
                    if (!context.state.currentSession || receiveMsg.from !== context.state.currentSession.username) {
                        //右下角展示消息
                        Notification.info({
                            title: '【' + receiveMsg.fromNickName + '】发来一条消息',
                            message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) : receiveMsg.content,
                            position: 'bottom-right'
                        });
                        //小红点提示
                        Vue.set(context.state.isDot, context.state.currentAdmin.username + '#' + receiveMsg.from, true);
                    }
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage', receiveMsg);
                })
            }, error => {
                console.log(error);
            })
        }
    },
});
store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
});


export default store;
